<?php

namespace App\Imports;

use App\Models\Dorm;
use App\Models\DormMeter;
use App\Models\MeterType;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use PhpOffice\PhpSpreadsheet\Shared\Date;


class DormMeterImport implements ToCollection
{
    public $total = 0;
    public $success = 0;
    public $fail = 0;
    public $ignore = 0;

    public function __construct()
    {
        $this->total = 0;
        $this->success = 0;
        $this->fail = 0;
        $this->ignore = 0;
    }

    /**
     * @param Collection $collection
     */
    public function collection(Collection $rows)
    {
        $i = 0;
        foreach ($rows as $row) {
            if ($i++ > 0) {
                try {
                    $time = Date::excelToDateTimeObject($row[3]);
                    $dormCode = $row[0];
                    $dorm = Dorm::query()->where('code', $dormCode)->first();
                    $meterName = $row[1];
                    $meterReading = $row[2];
                    $meterType = MeterType::query()->where('name', $meterName)->first();
                    if ($dorm && $meterType) {
                        DormMeter::query()->firstOrCreate([
                            'dorm_id' => $dorm->id,
                            'meter_type_id' => $meterType->id,
                            'nfc_id' => $dormCode . '-' . $meterType->abbr . '1'
                        ], [
                            'dorm_id' => $dorm->id,
                            'meter_type_id' => $meterType->id,
                            'nfc_id' => $dormCode . '-' . $meterType->abbr . '1',
                            'last_reading' => $meterReading,
                            'last_reading_date' => $time
                        ]);
                        $this->success++;
                    } else {
                        $this->ignore++;
                    }
                } catch (Exception $exception) {
                    $this->fail++;
                }
            }
        }
    }
}
